package echat.future.cn.echat.my.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.view.View;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import echat.future.cn.echat.R;
import echat.future.cn.echat.databinding.ActivityPersonInfoBinding;
import echat.future.cn.echat.my.api.UserApi;
import echat.future.cn.echat.my.bean.AnchorBean;
import echat.future.cn.echat.my.bean.ImageBean;
import echat.future.cn.echat.my.bean.UserBean;
import echat.future.cn.echat.my.utils.HttpUtilsRequst;
import echat.future.cn.echat.my.utils.ImageLoadUtils;
import echat.future.cn.echat.my.utils.MeHelper;
import echat.future.cn.echat.my.utils.RxUtils;
import echat.future.cn.echat.my.utils.UserHelper;
import echat.future.cn.echat.my.weight.Navagation.AdapterNavagation;
import echat.future.cn.echat.my.weight.Navagation.IBaseNavagation;
import echat.future.cn.echat.my.weight.dialog.ChoosePicDialog;
import echat.future.cn.echat.my.weight.dialog.StringDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.http.Multipart;

public class PersonInfoActivity extends BaseActivity<ActivityPersonInfoBinding>{
    Dialog choosePicDialog;

    private String updateUrl = "";
    @Override
    public int layoutId() {
        return R.layout.activity_person_info;
    }

    @Override
    public IBaseNavagation navagation() {
        return new AdapterNavagation(this).setTitle("个人资料", 16, R.color.white).setBack(R.drawable.btn_back).setNavagationBackgroudColor(R.color.color_161823);
    }

    @SuppressLint("CheckResult")
    @Override
    public void initView() {
        bind.head.setOnClickListener(v -> showChooseDialog());
        //加载用户信息
        ImageLoadUtils.loadImage(this, UserHelper.getUser().getAvatar(),bind.head);
        bind.name.setText(UserHelper.getUser().getUsername()==null?"":UserHelper.getUser().getUsername());
        bind.sign.setText(UserHelper.getUser().getSign()==null?"":UserHelper.getUser().getSign());
        RxUtils.clickView(bind.update).subscribe(v->sumbimt());
        if(UserHelper.getUser().getUser_role() == UserBean.TYPE_ANCHOR) {
            bind.llAnchor.setVisibility(View.VISIBLE);
            loadMoreinfo();
        }else{
            bind.llAnchor.setVisibility(View.GONE);
        }
    }





    private void showChooseDialog(){
        if(choosePicDialog == null){
            choosePicDialog = new ChoosePicDialog.Builder(this)
                    .photoListenter(v -> choosePic())
                    .cameroListenter(v ->chooseCamero()).Builder();
        }
        choosePicDialog.show();
    }


    private void choosePic() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .compress(true)
                .cropCompressQuality(60)
                .minimumCompressSize(100)
                .enableCrop(true)
                .withAspectRatio(1, 1)
                .isCamera(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
        if(choosePicDialog!=null)
            choosePicDialog.dismiss();
    }


    private void chooseCamero() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .compress(true)
                .cropCompressQuality(90)
                .minimumCompressSize(100)
                .enableCrop(true)
                .withAspectRatio(1, 1)
                .isCamera(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
        if(choosePicDialog!=null)
            choosePicDialog.dismiss();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 图片选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                for(int i=0;i<selectList.size();i++) {
                    LocalMedia media = selectList.get(i);
                    String  headImgPath = media.getCompressPath();
                    updateUrl = headImgPath;
                    ImageLoadUtils.loadImage(this,updateUrl,bind.head);
                }
            }
            if (requestCode == 10) {
                showTags(data.getStringArrayListExtra("data"),data.getStringExtra("ids"));
            }
        }
    }

    private void sumbimt(){
        if(bind.sign.getText().toString().equals("")){
            toast("请输入正确的签名");
            return;
        }

        if(bind.name.getText().toString().equals("")){
            toast("请输入正确的签名");
            return;
        }
        if(bind.city.equals("") && isAnchor){
            toast("请输入城市地址");
            return;
        }
        MultipartBody.Part filr = null;
        try {
            if(!updateUrl.equals("")) {
                RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), new File(updateUrl));
                filr = MultipartBody.Part.createFormData("avatar", new File(updateUrl).getName(), requestBody);
            }else{
                filr = MultipartBody.Part.createFormData("","");
            }
        }catch (Exception e){

        }
        if(isAnchor) {
            new HttpUtilsRequst<>(this, HttpUtilsRequst.retrofitClient.create(UserApi.class).updateUserInfo(
                    UserHelper.getToken(),
                    bind.name.getText().toString(),
                    bind.sign.getText().toString(),
                    filr,
                    bind.height.getText().toString(),
                    bind.weight.getText().toString(),
                    bind.city.getText().toString(),
                    bind.llTag.getContentDescription().toString()
            )).setmOnRequstSuccessListener(new HttpUtilsRequst.OnRequstSuccessListener() {
                @Override
                public void onSuccss(Object o) {
                    setResult(RESULT_OK);
                    finish();
                }
            })
                    .start();
        }else{
            new HttpUtilsRequst<>(this, HttpUtilsRequst.retrofitClient.create(UserApi.class).updateUserInfo(
                    UserHelper.getToken(),
                    bind.name.getText().toString(),
                    bind.sign.getText().toString(),
                    filr
            )).setmOnRequstSuccessListener(new HttpUtilsRequst.OnRequstSuccessListener() {
                @Override
                public void onSuccss(Object o) {
                    setResult(RESULT_OK);
                    finish();
                }
            })
                    .start();
        }
    }

    public boolean isAnchor = false;
    /**
     * 加载更多信息
     */
    private void loadMoreinfo(){
        new HttpUtilsRequst<>(this,HttpUtilsRequst.retrofitClient.create(UserApi.class).getOneAnchor(UserHelper.getToken(),UserHelper.getUserId()))
                .setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<AnchorBean>) anchorBean -> {
                    isAnchor = true;
                    bind.llAnchor.setVisibility(View.VISIBLE);
                    bind.height.setText(anchorBean.getHeight());
                    bind.weight.setText(anchorBean.getWeight());
                    bind.city.setText(anchorBean.getCity());
                    if(anchorBean.getApperance()!=null && anchorBean.getApperance().size()>0)
                        bind.tag1.setText(anchorBean.getApperance().get(0).getSign());
                    if(anchorBean.getApperance()!=null && anchorBean.getApperance().size()>1)
                        bind.tag2.setText(anchorBean.getApperance().get(1).getSign());
                    bind.llTag.setOnClickListener(v -> {startActivityForResult(new Intent(PersonInfoActivity.this, SetTagActivity.class), 10);});
                    if(anchorBean.getApperance()!=null && anchorBean.getApperance().size()>1)
                        bind.llTag.setContentDescription(anchorBean.getApperance().get(0).getId()+","+anchorBean.getApperance().get(1).getId());
                    bind.height.setOnClickListener(v -> {
                        showHeightDialog();
                    });
                    bind.weight.setOnClickListener(v -> {showWeight();});
                })
                .start();
    }


    private Dialog heightDialog;

    private Dialog weight;

    private void showHeightDialog() {
        if (heightDialog == null) {
            heightDialog = new StringDialog.Builder(this)
                    .title("选择身高")
                    .datas(MeHelper.getHeight())
                    .comfirmListener(title -> {
                        bind.height.setText(title);
                    })
                    .builder();
        }
        heightDialog.show();
    }


    private void showWeight() {
        if (weight == null) {
            weight = new StringDialog.Builder(this)
                    .title("选择体重").datas(MeHelper.getWeight())
                    .comfirmListener(title -> {
                                bind.weight.setText(title);
                            }
                    )
                    .builder();
        }
        weight.show();
    }




    private List<String> selectTags = new ArrayList<>();
    private void showTags(List<String> tags,String ids) {
        bind.llTag.setVisibility(View.VISIBLE);
        bind.llTag.setContentDescription(ids==null?"":ids);
        selectTags.clear();
        selectTags.addAll(tags);
        bind.tag1.setText(tags.get(0));
        bind.tag2.setText(tags.get(1));
    }
}
